package util.crypto

import java.security.spec.PKCS8EncodedKeySpec
import java.security.{KeyFactory, Signature}
import util.StreamUtils
import java.io.{ByteArrayOutputStream, OutputStream, InputStream}

/**
 * Inspired by http://stackoverflow.com/questions/521101/using-sha1-and-rsa-with-java-security-signature-vs-messagedigest-and-cipher
 */
object RSASHA1Signer {
  def read(input: InputStream): Array[Byte] = {
    val bos = new ByteArrayOutputStream
    StreamUtils.copy(input, bos)
    bos.close
    bos.toByteArray
  }
}

class RSASHA1Signer(val encodedKey: Array[Byte]) {

  def this(input: InputStream) = this(RSASHA1Signer.read(input))

  val privateKey = {
    val keySpec = new PKCS8EncodedKeySpec(encodedKey)
    val kf = KeyFactory.getInstance("RSA")
    val pk = kf.generatePrivate(keySpec)
    pk
  };

  def sign(data: String): Array[Byte] = {
    val sig = Signature.getInstance("SHA1withRSA")
    sig.initSign(privateKey)

    sig.update((data).getBytes())
    val signature = sig.sign();
    signature
  }

}

object ScalaductRSASHA1Signer extends RSASHA1Signer(RSASHA1Signer.read(classOf[RSASHA1Signer].
  getResourceAsStream("scaladuct-private.der")))